# coding= utf-8

import sys
import codecs
import warnings
import pymongo
import json
import requests
from datetime import datetime
from dateutil.relativedelta import relativedelta
from bson import ObjectId
import time

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
warnings.filterwarnings("ignore")


class LastTwoMonth:

    def __init__(self):
        self.country_desc = ''
        # self.month = sys.argv[1]
        self.month = '2024-09'

        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["xp_analyse"]
        self.low_order = mydb["wt_low_order_v2"]

    def update_low_order_num(self):
        months = get_previous_two_months(self.month)
        asin_wait = []
        for item in self.low_order.find({"month": self.month}):
            country_arr = []
            country_desc = item.get('country_desc')
            if country_desc == '美国':
                country_arr = ['US']
            elif country_desc == '英国':
                country_arr = ['UK']
            elif country_desc == '欧洲四国':
                country_arr = ['FR', 'DE', 'IT', 'ES']
            elif country_desc == '日本':
                country_arr = ['JP']
            elif country_desc == '加拿大':
                country_arr = ['CA']
            wait_item = {
                '_id': str(item.get('_id')),
                'group_name': item.get('group_name'),
                'asin': item.get('asin'),
                'country_arr': country_arr
            }
            asin_wait.append(wait_item)

            if len(asin_wait) >= 100:

                # 上月数据
                self.post_to_cep(asin_wait, months[1])

                # 停顿1s
                time.sleep(1)

                # 上上月数据
                self.post_to_cep(asin_wait, months[0], False)
                asin_wait = []

        # 最后仍有部分asin，一次性请求
        if len(asin_wait):
            # 上月数据
            self.post_to_cep(asin_wait, months[1])

            # 停顿1s
            time.sleep(1)

            # 上上月数据
            self.post_to_cep(asin_wait, months[0], False)

    # 将asin发送到测评系统获取asin在改组的上月订单情况
    def post_to_cep(self, wait_list, month, is_last=True):
        # url = "http://local-sys.com/common/analyse/get_last_low"
        url = "https://wangting.wszzl.cn/common/analyse/get_last_low"
        json_data = {
            'asins': json.dumps(wait_list),
            'month': month
        }

        response = requests.post(url, data=json_data)

        # 检查请求是否成功
        if response.status_code == 200:
            data = response.json()
            if data['status']:
                for item in data['data']:
                    if is_last:
                        self.low_order.update_one({'_id': ObjectId(item.get('_id'))}, {"$set": {"last_order": item.get('last_month')}})
                        print(item.get('_id') + '更新上月' + month + '订单量：' + str(item.get('last_month')))
                    else:
                        self.low_order.update_one({'_id': ObjectId(item.get('_id'))}, {"$set": {"last_last_order": item.get('last_month')}})
                        print(item.get('_id') + '更新上上月' + month + '订单量：' + str(item.get('last_month')))
            else:
                print(data['msg'])
        else:
            # 如果请求不成功，打印错误信息
            print("请求失败，状态码：", response.status_code)
            print(response.text)  # 可以打印出服务器返回的错误信息


def get_previous_two_months(month_str):
    year, month = map(int, month_str.split('-'))
    start_date = datetime(year, month, 1)

    prev_month_1_better = start_date - relativedelta(months=1)
    prev_month_2_better = prev_month_1_better - relativedelta(months=1)

    # 格式化输出
    previous_months = [prev_month_2_better.strftime('%Y-%m'), prev_month_1_better.strftime('%Y-%m')]
    return previous_months


last = LastTwoMonth()
last.update_low_order_num()
